package cn.sycoder.controller;

import cn.sycoder.entity.Menu;
import cn.sycoder.entity.Module;
import cn.sycoder.entity.Role;
import cn.sycoder.exception.BusinessException;
import cn.sycoder.mapper.MenuMapper;
import cn.sycoder.mapper.ModuleMapper;
import cn.sycoder.resp.Code;
import cn.sycoder.resp.Resp;
import cn.sycoder.resp.RespCode;
import cn.sycoder.service.IMenuService;
import cn.sycoder.service.IModuleService;
import cn.sycoder.utils.MenusUtil;
import cn.sycoder.vo.MenuNodeVo;
import cn.sycoder.vo.MenuVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨润发
 * @since 2024-10-21
 */
@RestController
@RequestMapping("/api/Module")
@Api(tags = "菜单管理")
@Transactional(rollbackFor = Exception.class)
public class ModuleController {


    @Autowired
    IMenuService menuService; // 注入菜单service

    @Autowired
    MenuMapper menuMapper;

    @PostMapping("/list")
    @ApiOperation(value = "菜单管理-获取菜单Module/list")
    public Map<String, Object> moduleList() {

        List<Menu> menus = null;
        try {
            // 先找没有子菜单的，再去查询有子菜单的
            menus = menuService.list();
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }

        List<MenuVo> parentMenus = new ArrayList<>();
        List<MenuVo> sonMenus = new ArrayList<>();
        for (Menu menu : menus) {
            MenuVo menuVo = new MenuVo();
            BeanUtils.copyProperties(menu, menuVo);
            if (menu.getPid() == null) {
                parentMenus.add(menuVo);
            }
            sonMenus.add(menuVo);
        }

        // 排序
        List<MenuVo> parentOrderMenus = parentMenus.stream()
                .sorted(Comparator.comparing(MenuVo::getOrderValue))
                .collect(Collectors.toList());

        for (MenuVo orderMenu : parentOrderMenus) {
            List<MenuVo> child = MenusUtil.getChild(orderMenu.getId(), sonMenus);
            List<MenuVo> collect = child.stream()
                    .sorted(Comparator.comparing(MenuVo::getOrderValue))
                    .collect(Collectors.toList());
            orderMenu.setMenus(collect);
        }

        // 创建响应结果
        HashMap<String, Object> response = new HashMap<>();
        response.put("data", parentOrderMenus);
        return response;
    }


    // 获取父级菜单
    @PostMapping("/nodes")
    @ApiOperation(value = "菜单管理-获取父级菜单Module/nodes")
    public Resp moduleNodes() {

        List<MenuNodeVo> menuNodeVos = null;
        try {
            menuNodeVos = menuMapper.selectNodes();
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }
        Resp resp = new Resp();
        resp.setData(menuNodeVos);
        return resp;
    }


    @PostMapping("/save")
    @ApiOperation(value = "菜单管理-根据菜单获取数据")
    public Map<String, Object> moduleSave(@RequestParam(value = "moduleId", required = false) Long menuId,
                                          @RequestParam(value = "parentId", required = false) Long parentId,
                                          @RequestParam(value = "moduleIcon") String menuIcon,
                                          @RequestParam(value = "moduleUrl") String menuUrl,
                                          @RequestParam(value = "moduleName") String menuName,
                                          @RequestParam(value = "moduleOrder") Integer menuOrder) {

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        Menu menu = new Menu();
        menu.setId(menuId);
        menu.setPid(parentId);
        menu.setIcon(menuIcon);
        menu.setUrl(menuUrl);
        menu.setMenuName(menuName);
        menu.setOrderValue(menuOrder);

        // 保存或更新方法
        boolean ret = false;
        try {
            if (menu.getId() != null) {
                // 有id表示更新操作
                ret = menuService.updateById(menu);
            } else {
                // 无id表示保存操作
                ret = menuService.save(menu);
            }
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }

        if (ret) {
            response.put("success", true);
        } else {
            response.put("msg", "服务器异常！");
        }
        return response;
    }


    @DeleteMapping("/delete")
    @ApiOperation(value = "菜单管理-删除菜单")
    public Map<String, Object> moduleDelete(@RequestParam(value = "ids") List<Long> moduleIds) {

        // 创建响应结果
        Map<String, Object> response = new HashMap<>();

        // 执行删除操作
        boolean ret = false;
        try {
            for (Long moduleId : moduleIds) {
                ret = menuService.removeById(moduleId);
            }
        } catch (BusinessException e) {
            new BusinessException(Code.BUSINESS_ERR, "处理业务异常，请稍后再试！");
        }

        if (ret) {
            response.put("success", true);
        } else {
            response.put("msg", "服务器异常");
        }
        return response;
    }
}
